package org.example.student_dormitory.controller;

import net.sf.json.JSONObject;
import org.example.student_dormitory.dto.Result;
import org.example.student_dormitory.entity.Admin;
import org.example.student_dormitory.service.AdminService;
import org.example.student_dormitory.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    private AdminService adminService = new AdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求响应编码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");

        // 获取前端请求数据
        String method = req.getParameter("method");
        // 预防空指针异常
        if ("login".equals(method)) {
            login(req, resp);
        }else if ("logout".equals(method)) {
            logout(req, resp);
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 登录
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String dr = req.getParameter("dr");
        int d = Integer.parseInt(dr);

        // 调用业务逻辑层的登录方法
        Result<Admin> adminResult = adminService.login(username, password, d);
        if (adminResult.getCode() == 200){
            req.getSession().setAttribute("login_session",new Date());
        }
        // 将java对象转json字符串
        String json_str = JSONObject.fromObject(adminResult).toString();
        // 将json字符串响应给前端
        resp.getWriter().write(json_str);
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 退出
        req.getSession().invalidate();
        Result<Object> result = new Result<>(200, "Session已清空", null);
        // 将java对象转json字符串
        String json_str = JSONObject.fromObject(result).toString();
        // 将json字符串响应给前端
        resp.getWriter().write(json_str);
    }

}
